<template>
  <div class="h-screen flex bg-gray-50">
    <!-- 侧边栏 -->
    <div class="w-64 bg-white shadow-lg flex flex-col">
      <!-- 顶部logo和导航栏（只保留一份） -->
      <div class="p-4 border-b">
        <div class="flex items-center">
          <div class="w-10 h-10 bg-gradient-to-br from-pink-500 to-rose-600 rounded-xl flex items-center justify-center">
            <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
            </svg>
          </div>
          <div class="ml-3">
            <h2 class="text-lg font-semibold text-gray-900">AI恋爱大师</h2>
            <p class="text-sm text-gray-500">情感咨询助手</p>
          </div>
        </div>
      </div>
      <!-- deepseek风格主导航栏 -->
      <div class="px-4 pt-2 pb-2 flex flex-col gap-2 border-b">
        <router-link
          to="/home"
          class="flex items-center p-3 text-gray-700 rounded-lg hover:bg-gray-100 transition-colors"
        >
          <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
          </svg>
          返回主页
        </router-link>
        <div class="flex items-center p-3 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer"
             @click="goManusChat"
             :class="status === 2 ? 'bg-gray-200 font-bold' : ''">
          <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
          </svg>
          超级智能体
        </div>
        <div class="flex items-center p-3 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer text-pink-500"
             :class="status === 1 ? 'bg-pink-100 font-bold' : ''">
          <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" />
            <path d="M8 12l2 2 4-4" stroke="currentColor" stroke-width="2" fill="none" />
          </svg>
          用户记忆
        </div>
      </div>
      <!-- 历史会话列表，紧跟在导航栏下方 -->
      <div class="flex-1 overflow-y-auto">
        <ChatHistoryList
          :uid="uid"
          :selectedChatId="chatId"
          :status="status"
          @select="handleSelect"
        />
      </div>
      <!-- 用户信息 -->
      <div class="p-4 border-t">
        <div class="relative" ref="userMenuRef">
          <button
            @click="showUserMenu = !showUserMenu"
            class="flex items-center space-x-3 w-full p-2 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <div class="w-8 h-8 user-avatar rounded-full flex items-center justify-center">
              <span class="text-white text-sm font-medium">{{ userInitial }}</span>
            </div>
            <span class="text-sm text-gray-700 flex-1 text-left">{{ authStore.username }}</span>
          </button>
          <!-- 用户菜单 -->
          <div
            v-show="showUserMenu"
            class="absolute bottom-full left-0 mb-2 w-full bg-white rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-50"
          >
            <div class="py-1">
              <button
                @click="handleLogout"
                class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
              >
                注销登录
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 主聊天区域 -->
    <div class="flex-1 flex flex-col">
      <!-- 聊天头部 -->
      <div class="bg-white border-b px-6 py-4 flex items-center">
        <div class="flex items-center">
          <div class="w-10 h-10 ai-avatar rounded-full flex items-center justify-center">
            <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
            </svg>
          </div>
          <div class="ml-3">
            <h3 class="text-lg font-semibold text-gray-900">AI恋爱大师</h3>
            <p class="text-sm text-gray-500">在线 • 随时为您提供情感建议</p>
          </div>
        </div>
      </div>
      <!-- 聊天记录 -->
      <div class="flex-1 overflow-y-auto p-6" ref="chatContainer">
        <div class="max-w-4xl mx-auto space-y-6">
          <!-- 聊天内容时显示新对话按钮 -->
          <div v-if="!showWelcome && messages.length > 0" class="flex justify-center mb-4">
            <button
              @click="startNewConversation"
              class="inline-flex items-center px-4 py-2 bg-white border border-pink-300 rounded-full text-sm text-pink-500 hover:bg-pink-50 transition-colors font-medium shadow-sm"
            >
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
              开启新对话
            </button>
          </div>
          <div v-if="showWelcome" class="h-full flex flex-col items-center justify-center p-8">
            <div class="w-16 h-16 ai-avatar rounded-full flex items-center justify-center mb-6">
              <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
            </div>
            <h2 class="text-2xl font-bold text-gray-900 mb-4">AI恋爱大师</h2>
            <p class="text-gray-600 text-center max-w-md leading-relaxed">
              我是您的专业恋爱咨询师，可以为您提供情感建议、约会技巧、沟通指导等服务。请告诉我您想要咨询的问题。
            </p>
          </div>
          <div v-else>
            <div v-for="(message, index) in messages" :key="index + '-' + message.type + '-' + message.content.slice(0,10)" class="flex" :class="message.type === 'user' ? 'justify-end' : 'justify-start'">
              <!-- AI消息 -->
              <div v-if="message.type === 'ai'" class="flex items-start max-w-[80%]">
                <div class="w-8 h-8 ai-avatar rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                  <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                  </svg>
                </div>
                <div class="chat-bubble chat-bubble-ai text-left">
                  <div v-if="message.loading" class="loading-dots">
                    <div class="loading-dot"></div>
                    <div class="loading-dot"></div>
                    <div class="loading-dot"></div>
                  </div>
                  <MarkdownRenderer v-else :content="message.content" class="text-left" />
                </div>
              </div>
              <!-- 用户消息 -->
              <div v-else class="flex items-start max-w-[80%] flex-row-reverse">
                <div class="w-8 h-8 user-avatar rounded-full flex items-center justify-center ml-3 flex-shrink-0">
                  <span class="text-white text-xs font-medium">{{ userInitial }}</span>
                </div>
                <div class="chat-bubble chat-bubble-user text-left">
                  <div class="whitespace-pre-wrap text-left">{{ message.content }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 输入区域 -->
      <div class="bg-white border-t p-6">
        <div class="max-w-4xl mx-auto">
          <div class="flex space-x-4">
            <div class="flex-1 relative">
              <textarea
                v-model="inputMessage"
                @keydown="handleKeyDown"
                placeholder="请输入您的恋爱问题..."
                class="w-full p-4 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-pink-500 focus:border-transparent"
                rows="1"
                style="min-height: 56px; max-height: 200px;"
                :disabled="isLoading"
              ></textarea>
            </div>
            <div class="flex space-x-2">
              <button
                @click="toggleNetworkSearch"
                :class="[
                  'px-4 py-3 rounded-lg border transition-colors flex items-center justify-center',
                  networkSearch 
                    ? 'bg-blue-500 text-white border-blue-500' 
                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
                ]"
                :disabled="isLoading"
                title="联网搜索"
              >
                <svg class="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                <span class="text-xs">联网搜索</span>
              </button>
              <transition name="fade">
                <div v-if="showNetworkTip" class="absolute left-0 bottom-full mb-2 px-3 py-1 bg-blue-500 text-white text-xs rounded shadow-lg z-10">
                  已启动联网搜索工具
                </div>
              </transition>
              <button
                @click="isLoading ? handleAbort() : sendMessage()"
                :disabled="!isLoading && !inputMessage.trim()"
                :class="[
                  'px-6 py-3 rounded-lg transition-colors',
                  isLoading 
                    ? 'bg-red-500 text-white hover:bg-red-600' 
                    : 'bg-pink-500 text-white hover:bg-pink-600 disabled:opacity-50 disabled:cursor-not-allowed'
                ]"
              >
                <svg v-if="!isLoading" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                </svg>
                <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { createChat, createSSEConnection } from '../api/index'
import { fetchChatList, fetchChatDetail } from '../api/chat'
import MarkdownRenderer from '../components/MarkdownRenderer.vue'
import ChatHistoryList from './ChatHistoryList.vue'
import { useChatStore } from '../stores/chat'

const router = useRouter()
const authStore = useAuthStore()
const chatStore = useChatStore()

const props = defineProps({
  chatId: String,
  historyMessages: {
    type: Array,
    default: () => []
  },
  historyMode: Boolean
})

const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const chatId = ref('')
const uid = ref(localStorage.getItem('uid') || '1')
const showUserMenu = ref(false)
const userMenuRef = ref(null)
const chatContainer = ref(null)
const networkSearch = ref(false)
const showNetworkTip = ref(false)
const hasSentFirstMessage = ref(false)
const status = ref(1) // 恋爱大师页面固定为1
const showWelcome = ref(true)
let hasRefreshedHistory = false;
let lastCreatedChatId = '';

// 用户名首字母
const userInitial = computed(() => {
  return authStore.username ? authStore.username.charAt(0).toUpperCase() : 'U'
})

// 跳转到超级智能体页面
function goManusChat() {
  router.push('/manus-chat')
}

// 选择历史会话
async function handleSelect({ chatId: selectedId, uid: selectedUid }) {
  if (!selectedId) {
    showWelcome.value = true
    messages.value = []
    inputMessage.value = ''
    chatId.value = ''
    uid.value = selectedUid
    console.log('[handleSelect] 调用initChat前', typeof initChat)
    await initChat()
    console.log('[handleSelect] initChat已await完成')
    return
  }
  showWelcome.value = false
  chatId.value = selectedId
  uid.value = selectedUid
  fetchChatDetail({ uid: Number(selectedUid), chatId: String(selectedId) })
    .then(res => {
      messages.value = (res.data.data?.messages || []).map(m => ({
        type: m.messageType === 'USER' ? 'user' : 'ai',
        content: m.text,
        timestamp: m.timestamp || Date.now()
      }))
    })
    .catch(err => {
      console.error('getChatMemory接口异常:', err)
    })
}

// 切换联网搜索
const toggleNetworkSearch = () => {
  networkSearch.value = !networkSearch.value
  if (networkSearch.value) {
    showNetworkTip.value = true
    setTimeout(() => showNetworkTip.value = false, 1500)
  }
}

// 全局变量
let sseController = null
let aiMessageIndex = null // 记录当前AI消息索引

// 监听historyMessages变化，若有则展示历史消息
watch(() => props.historyMessages, (val) => {
  if (props.historyMode && Array.isArray(val)) {
    // 兼容新格式：messageType区分用户/AI，text为内容
    messages.value = val.map(m => ({
      type: m.messageType === 'USER' ? 'user' : 'ai',
      content: m.text,
      timestamp: Date.now()
    }))
  }
}, { immediate: true })

// 发送消息
const sendMessage = async () => {
  console.log('[sendMessage] 入口', { input: inputMessage.value, isLoading: isLoading.value, chatId: chatId.value, uid: uid.value })
  if (!inputMessage.value.trim() || isLoading.value) {
    console.log('[sendMessage] 输入为空或正在加载，return')
    return;
  }
  if (showWelcome.value) showWelcome.value = false;
  hasRefreshedHistory = false;
  const isNewChat = lastCreatedChatId && (chatId.value === lastCreatedChatId);
  // chatId 必须有值
  const useChatId = props.chatId || chatId.value
  if (!useChatId) {
    console.error('[sendMessage] chatId 不能为空，return')
    return
  }
  if (!uid.value) {
    console.error('[sendMessage] 没有uid，return')
    return
  }
  const userMessage = inputMessage.value.trim()
  messages.value.push({
    type: 'user',
    content: userMessage
  })
  aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '',
    loading: true
  })
  inputMessage.value = ''
  isLoading.value = true
  await nextTick()
  scrollToBottom()
  if (!hasSentFirstMessage.value) {
    hasSentFirstMessage.value = true
    chatStore.loadChatList(Number(uid.value), 1)
  }
  const backendMessage = networkSearch.value ? `使用联网搜索工具进行查询：${userMessage}` : userMessage
  try {
    console.log('[sendMessage] 调用createSSEConnection', {
      url: '/ai/love_app/chat/sse/emitter',
      params: { message: backendMessage, chatId: useChatId, uid: Number(uid.value), networkSearch: networkSearch.value }
    })
    sseController = createSSEConnection(
      '/ai/love_app/chat/sse/emitter',
      { message: backendMessage, chatId: useChatId, uid: Number(uid.value), networkSearch: networkSearch.value },
      (data) => {
        console.log('[sendMessage] SSE onMessage 回调', data)
        if (messages.value[aiMessageIndex] && messages.value[aiMessageIndex].loading) {
          messages.value[aiMessageIndex].loading = false
        }
        messages.value[aiMessageIndex].content += data
        nextTick(() => scrollToBottom())
        if (isNewChat && !hasRefreshedHistory) {
          chatStore.loadChatList(Number(uid.value), 1)
          hasRefreshedHistory = true
        }
      },
      (error) => {
        console.error('[sendMessage] SSE onError 回调', error)
        isLoading.value = false
        if (messages.value[aiMessageIndex]) {
          messages.value[aiMessageIndex].loading = false
          if (error?.limit) {
            messages.value[aiMessageIndex].content = error.message
          } else {
            messages.value[aiMessageIndex].content += '\n[连接中断]'
          }
        }
      },
      () => {
        console.log('[sendMessage] SSE onComplete 回调')
        isLoading.value = false
        if (messages.value[aiMessageIndex]) {
          messages.value[aiMessageIndex].loading = false
          messages.value[aiMessageIndex].content = messages.value[aiMessageIndex].content.trim()
        }
      }
    )
    console.log('[sendMessage] createSSEConnection已调用，controller:', sseController)
  } catch (error) {
    console.error('[sendMessage] try-catch异常', error)
    if (messages.value[aiMessageIndex]) {
      messages.value[aiMessageIndex].loading = false
      messages.value[aiMessageIndex].content += '\n[发送失败]'
    }
    isLoading.value = false
  }
}

// 键盘事件处理
const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 注销处理
const handleLogout = () => {
  authStore.logout()
  router.push('/login')
  showUserMenu.value = false
}

// 点击外部关闭用户菜单
const handleClickOutside = (event) => {
  if (userMenuRef.value && !userMenuRef.value.contains(event.target)) {
    showUserMenu.value = false
  }
}

// 初始化聊天
const initChat = async () => {
  console.log('[initChat] 被执行')
  try {
    console.log('[initChat] 调用createChat...')
    const response = await createChat()
    console.log('[initChat] createChat接口响应:', response)
    if (!response) {
      throw new Error('create接口无响应')
    }
    if (response.chatId && response.id) {
      chatId.value = response.chatId
      uid.value = response.id
      authStore.uid = response.id
      console.log('[initChat] 设置成功 - chatId:', chatId.value, 'uid:', uid.value)
    } else if (response.id) {
      chatId.value = response.id
      uid.value = response.id
      authStore.uid = response.id
      console.log('[initChat] 只有id字段 - chatId:', chatId.value, 'uid:', uid.value)
    } else {
      throw new Error('响应中缺少必要字段（chatId或id）')
    }
    showWelcome.value = true
    messages.value = []
    inputMessage.value = ''
  } catch (error) {
    console.error('[initChat] 异常:', error)
    if (error.message?.includes('403') || error.response?.status === 403) {
      router.push('/login')
      return
    }
    chatId.value = 'test-chat-id'
    uid.value = 'test-uid'
    authStore.uid = 'test-uid'
    showWelcome.value = true
    messages.value = []
    inputMessage.value = ''
    console.log('[initChat] 使用测试值 - chatId:', chatId.value, 'uid:', uid.value)
  }
}

// 开启新对话
const startNewConversation = async () => {
  messages.value = []
  inputMessage.value = ''
  isLoading.value = false
  chatId.value = ''
  uid.value = null
  showWelcome.value = true // 新建对话后回到欢迎页
  await initChat()
  scrollToBottom()
}

// 终止AI回复
const handleAbort = () => {
  // 1. 终止SSE流
  if (sseController && typeof sseController.abort === 'function') {
    sseController.abort()
  }
  // 2. 立即允许输入
  isLoading.value = false
  // 3. 给AI消息加"回复已终止"标记
  if (messages.value[aiMessageIndex]) {
    messages.value[aiMessageIndex].loading = false
    messages.value[aiMessageIndex].content += '\n[回复已终止]'
  }
}

onMounted(() => {
  chatStore.loadChatList(Number(uid.value), status.value)
  initChat()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.chat-bubble-ai {
  background: #fff;
  color: #222;
  border-radius: 1.5rem;
  padding: 0.75rem 1.25rem;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.04);
  border: 1px solid #f1f1f1;
  font-size: 1rem;
  line-height: 1.8;
  word-break: break-word;
}
.chat-bubble-user {
  background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
  color: #fff;
  border-radius: 1.5rem;
  padding: 0.75rem 1.25rem;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.08);
  font-size: 1rem;
  line-height: 1.8;
  word-break: break-word;
}
</style> 